<?php
/**
 * 短信模块
 */
namespace app\api\controller\user;

use app\api\controller\Common;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class Sms extends Common {
    protected $data;
    public function initialize()
    {
        $this->data = $this->request->except(['sign','accessKey','token']);
    }
    
    /**
     * 发送短信
     */
    public function sendCode(){
        $data = $this->data;
        $valid_res = $this->validate([
            'mobile' => $data['mobile'],
        ],'app\api\validate\Sms');
        if(true !== $valid_res){
            $this->showError($valid_res, 401);
        }

        $code = rand_string(4, 1);
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $data['mobile'],
            "signName" => "中国",
            "templateCode" => "sms_123"
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSms($sendSmsRequest);
        if($res['Code'] == 'OK'){
            $this->showSuccess('发送成功', $code);
            cache('reg-'.$data['mobile'], $code, 300);
        }
        else{
            $this->showError($res['Message'], $res['Code']);
        }
            

    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient()
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => config('aliAccessKeyId'),
            // 您的AccessKey Secret
            "accessKeySecret" => config('aliaccessKeySecret'),
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }
}
